<!--
 * @Description: 虚拟列表
 * @Author: zhanyinjia
 * @Date: 2022-04-17 22:44:12
 * @LastEditors: zhanyinjia
 * @LastEditTime: 2022-09-28 15:36:41
-->
<template>
  <ul class="box" ref="box"></ul>
</template>

<script>
let list = [],
  total = 500
for (let i = 0; i < total; i++) {
  list.push({ id: i, name: i })
}
export default {
  data() {
    return {
      currentTotal: 0,
      currentIndex: 0,
      list,
      total,
      step: 10
    }
  },
  mounted() {
    this.createEle()
  },
  methods: {
    createEle() {
      this.currentTotal += this.step
      if (this.currentTotal < this.total) {
        requestAnimationFrame(() => {
          //分片渲染，因为requestAnimationFrame是一个宏任务，会等待ui渲染完成后再继续执行
          let fragment = document.createDocumentFragment()
          for (let i = 0; i < this.step; i++) {
            let li = document.createElement('li')
            li.className = 'box-li'
            li.innerHTML = this.list[++this.currentIndex].name
            fragment.appendChild(li)
          }
          this.$refs.box.appendChild(fragment)
          this.createEle()
        })
      }
    }
  }
}
</script>

<style lang="less" scope>
.box {
  width: 300px;
  height: 320px;
  border: 1px solid rgb(211, 209, 209);
  overflow-y: auto;
  margin: 20px 0;
  .box-li {
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    box-sizing: border-box;
    border-bottom: 1px solid rgb(211, 209, 209);
  }
}
</style>
